package com.demo.seata.tcc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.demo.seata.tcc.domain.TestUser;
import com.demo.seata.tcc.service.TccUserService;
import com.demo.seata.tcc.service.TestUserService;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.rm.tcc.api.BusinessActionContextParameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author
 * @since
 */
@Component
@Slf4j
public class TccUserServiceImpl implements TccUserService {
  @Autowired
  TestUserService testUserService;

  @Override
  @Transactional
  public boolean addUserTry(TestUser testUser) {
    log.info("SEATA TCC trigger try :  TccUserServiceImpl.addUserTry ");
    return testUserService.save(testUser);
  }

  @Override
  public boolean addUserConfirm(BusinessActionContext context) {
    log.info("SEATA TCC trigger confirm :TccUserServiceImpl.addUserConfirm: {}", context);
    return true;
  }

  @Override
  @Transactional
  public boolean addUserCancel(BusinessActionContext context) {
    log.info("SEATA TCC trigger cancel :TccUserServiceImpl.addUserCancel:{}", context);
    TestUser testUser  = ((JSONObject)context.getActionContext("testUser")).toJavaObject(TestUser.class);
    log.info("SEATA TCC trigger cancel : testUser : {}", testUser);
    Map delCondition = new HashMap<String, String>();
    delCondition.put("idno", testUser.getIdno());
    testUserService.removeByMap(delCondition);
    return true;
  }
}
